//
//  OvertimeMainViewController.swift
//  mggz
//
//  Created by QinWei on 2018/4/16.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
import Moya
class OvertimeMainViewController: UIViewController {
    var currentProject: ProjectModel?
    var selectDate: Date? //点击的时间
    var detailModel:OvertimeDetailModel?
    var isCanApply:Bool? //
    var timeWorkAlertView:TWLAlertView?
    var msTime:String? = "17:30" //默认数据
    var msWorkPoints:String? = "0.5" //默认数据
    //var reasonTextView:UITextView?
    var reasonText:String? = "" //申请理由
    var isHaveDetail:Bool? = false //详细数据是否为空
    var currentDate:Date? //当前时间
    var currentDateStr:String? //当前时间的字符串格式
    var isApplication:Bool? = false //判断时间是否在未来时间
    var overtimeEndTime:String?
    var overtimeStartTime:String?
    var overTimeDateStr:String? //加班日期
    var chooseStartTime:String?
    var systemStartTime:String?
    //时间范围的字段
    var startRange:String?
    var endRange:String?
    var isCalenlar:Bool?
    
    @IBOutlet weak var tableH: NSLayoutConstraint!
    
    var commitButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        button.setTitle("提交", for: .normal)
        button.titleLabel?.font = wwFont_Medium(16)
        button.layer.cornerRadius = 10
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        return button
    }()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.overTimeDateStr = dateToString(date: self.selectDate!)
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.getOverTimeQuantaum()
        self.getSystemTime {
            
        }
        self.setupTableView()
        self.getOvertimeDetailData()
    }
    fileprivate func setupTableView(){
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        if self.isCalenlar == false{
            self.tableH.constant = 64
        }else{
            self.tableH.constant = 85
        }
        self.tableView.register(UINib.init(nibName: "OvertimeApplyCell", bundle: nil), forCellReuseIdentifier: "apply")
        self.tableView.register(UINib.init(nibName: "OvertimeReasonCell", bundle: nil), forCellReuseIdentifier: "reason")
        self.tableView.register(UINib.init(nibName: "OvertimeStateCell", bundle: nil), forCellReuseIdentifier: "state")
        self.tableView.register(UINib.init(nibName: "OvertimeReturnCell", bundle: nil), forCellReuseIdentifier: "return")
    }
    
    fileprivate func getOverTimeQuantaum(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.currentProject?.demandBaseMigrantWorkerID else{
            return
        }
        guard (self.selectDate != nil) else {
            return
        }
        let signedDay : String = dateToString(date: self.selectDate!)
        
        
        LCAPiSubManager.request(.GetOverTimeQuantaum(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, workDate: signedDay, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{

                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                    return
                }
                
                let endTime = resultDic["EndTime"] as? String
                let startTime = resultDic["BeginTime"] as? String
                
                self.startRange = self.getDateStrWithHHSS(dateStr: startTime!)
                self.msTime = self.startRange
                self.endRange = self.getDateStrWithHHSS(dateStr: endTime!)
                
                let index1 = startTime?.index(of: "T")
                self.systemStartTime = String((startTime?.prefix(upTo: index1!))!)

                self.overtimeEndTime = endTime?.replacingOccurrences(of: "T", with: " ")
                self.overtimeStartTime = startTime?.replacingOccurrences(of: "T", with: " ")
                self.chooseStartTime = self.overtimeStartTime
                
                
                self.tableView.reloadData()
            }
        }
    }
    fileprivate func getSystemTime(_ completion:@escaping () -> Void){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        
      LCAPiSubManager.request(.GetSystemTime(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? String else{
                    return
                }
                let index1 = resultDic.index(of: "T")
                let index2 = resultDic.index(of: ".")
                let realDate = String(resultDic.prefix(upTo: index2!))
                
                self.currentDate = dateStringWithTToDate(dateString: realDate)
                let currentDateStr1 = dateToString(date: self.currentDate!)
                if self.selectDate! < self.currentDate!{
                    self.isApplication = false
                }else{
                    self.isApplication = true
                }
                if self.overTimeDateStr == currentDateStr1{
                    self.isApplication = true
                }
                self.currentDateStr = String(resultDic.prefix(upTo: index1!))
                completion()
                self.tableView.reloadData()
            }
        }
    }
    fileprivate func getOvertimeDetailData(){
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.currentProject?.demandBaseMigrantWorkerID else{
            return
        }
        guard (self.selectDate != nil) else {
            return
        }
        let signedDay : String = dateToString(date: self.selectDate!)
       
    LCAPiSubManager.request(.GetOvertimeApplyInfo(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, workDate: signedDay, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    self.isHaveDetail = false
                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                    return
                }
             self.isHaveDetail = true
            self.detailModel = Mapper<OvertimeDetailModel>().map(JSONObject: resultDic)
                if ((self.detailModel?.WorkBeginTime) != nil){
                    self.msTime = self.getDateStrWithHHSS(dateStr: (self.detailModel?.WorkBeginTime)!)
                }
                if ((self.detailModel?.ApplyWorkDays) != nil){
              self.msWorkPoints = String(self.detailModel!.ApplyWorkDays!)
            }
            //self.detailModel?.ApplyState = 2
            self.reasonText = self.detailModel?.Reason
            self.tableView.reloadData()
        }
    }
}
    @objc fileprivate func doCommitAction(){
        
        var guid: String?
        var orderNo: String?
        let orderConfigId = "8efb1163-74b5-b61b-d7e0-b821a266bb40"
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success{
                guid = response.value
            }
            else {
                
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
            if response.success {
                orderNo = response.value
            }
            else {
                
            }
            dispatchGroup.leave()
        }
        dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
                WWError("获取guid出错")
                return
            }
            guard orderNo != nil else {
                WWError("获取orderNo出错")
                return
            }
            guard (self.reasonText?.count)! > 0 else {
                QWTextonlyHud("加班原因不能为空!", target: self.view)
                return
            }
            guard let DemandBaseMigrantWorkerID = self.currentProject?.demandBaseMigrantWorkerID else{
                return
            }
            guard let accountId = WWUser.sharedInstance.accountId else{
                return
            }
            guard let businessChangerID = self.currentProject?.businessChangerID else{
                WWInform("当前所在劳务公司未设置管理员！")
                return
            }
            guard let projectID = self.currentProject?.projectID else{
                return
            }
            
            guard (self.overtimeEndTime != nil) else{
                return
            }
            guard (self.overTimeDateStr != nil) else{
                return
            }
            guard (self.chooseStartTime != nil) else{
                return
            }
            let jsonModel = [
                "ID": guid!,
                "Form": [
                    "DemandBaseMigrantWorker": [
                        "ID": DemandBaseMigrantWorkerID,
                            "ConstructionProject": [
                                "ID": projectID,//项目ID
                                "Company": [
                                    "CompanyCharger": [
                                        "BusinessChanger": [
                                            "ID":businessChangerID
                                        ]
                                    ]
                                ]
                            ]
                    ],
                    "WorkDate": self.overTimeDateStr!,//加班日期
                    "WorkBeginTime": self.chooseStartTime!,//开工时间
                    "WorkEndTime": self.overtimeEndTime!,//结束时间
                    "ApplyWorkHours": 0,//加班时长
                    "ApplyWorkDays": self.msWorkPoints!,//记工数
                    "Reason": self.reasonText!,//加班原因
                    "OrderNo": orderNo!
                ]
                ] as [String : Any]
           
            let jsonData:String = putDictionaryToJSONString(dictionary: jsonModel as NSDictionary)
            
            
            QWTextWithStatusHud("开始提交", target: self.view)
        LCAPiSubManager.request(.ApplicationOvertimeAction(orderId: guid!, jsonData: jsonData, AccountId: accountId, approvalNote: "提交审批")) { (result) in
            if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        return
                    }
                
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                QWHudDiss(self.view)
                QWTextonlyHud("提交成功", target: self.view)
                let cell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 0)) as! OvertimeApplyCell
                cell.timeSelectButton.isHidden = true
                cell.workSelectButton.isHidden = true
                
                self.commitButton.isEnabled = false
                self.commitButton.backgroundColor = UIColor.lightGray
            self.tableView.reloadData()
                
            }else{
                QWTextonlyHud("提交失败", target: self.view)
            }
            }
        }
        
    }
    
    
    fileprivate func getDateStrWithHHSS(dateStr:String) -> String?{
        let derange = dateStr.range(of: "T")
        let suffixStr = dateStr.suffix(from: (derange?.upperBound)!)
        let index2 = suffixStr.index(suffixStr.startIndex, offsetBy: 5)
        let resultStr = suffixStr.prefix(upTo: index2)
        
       return String(resultStr)
    }
    
}

extension OvertimeMainViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if self.isHaveDetail == false && self.isApplication == false{
            self.tableView.isHidden = true
        }else{
            self.tableView.isHidden = false
        }
        return 1
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            //无明细的时候
            if self.isHaveDetail == false || self.detailModel?.ApplyState == -2{
                if self.isApplication == true{
                   let cell : OvertimeApplyCell = tableView.dequeueReusableCell(withIdentifier: "apply") as! OvertimeApplyCell
                    cell.timeSelectButton.addTarget(self, action: #selector(timeSelectClick), for: .touchUpInside)
                    cell.workSelectButton.addTarget(self, action: #selector(workSelectButtonClick), for: .touchUpInside)
                    cell.workLabel.text = self.msWorkPoints
                    cell.timeLabel.text = self.msTime
                    if (self.startRange != nil) && (self.endRange != nil){
                         cell.rangeLabel.text = self.startRange! + "~" + self.endRange! + ")"
                    }
                    return cell
                }
         }
            
        //有明细的时候
        if self.isHaveDetail == true{
            
            let cell : OvertimeStateCell = tableView.dequeueReusableCell(withIdentifier: "state") as! OvertimeStateCell
            cell.setCellDataWithModel(self.detailModel!)
            return cell
        }
            
            
            
      }
       
        let cell : OvertimeReasonCell = tableView.dequeueReusableCell(withIdentifier: "reason") as! OvertimeReasonCell
        cell.reasonTextView.text = self.reasonText
        if self.detailModel?.ApplyState == -2 || self.isHaveDetail == false{
            cell.reasonTextView.isEditable = true
        }else{
            cell.reasonTextView.isEditable = false
        }
        
        
        
        cell.textViewDidChange = {(text) in
            self.reasonText = text
        }
        return cell
    }
    
    @objc fileprivate func timeSelectClick(){
        self.timeWorkAlertView = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let timeSelectView = OvertimeStartView.init(frame: CGRect(x: 0, y: 0, width: 280, height: 240))
        
        let timeDate = stringToTimeDate(dateString: self.startRange ?? "17:30")
        timeSelectView.datePicker.setDate(timeDate!, animated: true)
        timeSelectView.cancelButton.addTarget(self, action: #selector(timeSelectCancelClick), for: .touchUpInside)
        timeSelectView.selectedTime = {(value1,value2) in
            self.timeWorkAlertView?.cancleView()
            guard (self.systemStartTime != nil) else {
                QWTextonlyHud("无法设置时间", target: self.view)
                return
            }
            let chooseTime = self.systemStartTime! + " " + value2
            guard (self.overtimeStartTime != nil) else {
                QWTextonlyHud("未获取限定时间", target: self.view)
                return
            }
            guard (self.overtimeEndTime != nil) else {
                QWTextonlyHud("未获取限定时间", target: self.view)
                return
            }
            let chooseDate = stringToTimeHMSDate(dateString: chooseTime)
            let lessDate = stringToTimeHMSDate(dateString: self.overtimeStartTime!)
            let mostDate = stringToTimeHMSDate(dateString: self.overtimeEndTime!)
            if chooseDate! == lessDate! || chooseDate! == mostDate!{
                self.msTime = value1
                self.chooseStartTime = chooseTime
           self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }else if chooseDate! > lessDate! && chooseDate! < mostDate!{
                self.msTime = value1
                self.chooseStartTime = chooseTime
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }else{
                QWTextonlyHud("超出限定时间", target: self.view)
            }
        }
        self.timeWorkAlertView?.initWithCustomView(timeSelectView, frame: CGRect(x: 0, y: 0, width: 280, height: 240))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeWorkAlertView!)
    }
    
    @objc fileprivate func timeSelectCancelClick(){
        self.timeWorkAlertView?.cancleView()
        
    }
    
    @objc fileprivate func workSelectButtonClick(){
        self.timeWorkAlertView?.cancleView()
        self.timeWorkAlertView = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let worktSelectView = OvertimeWorkView.init(frame: CGRect(x: 0, y: 0, width: 280, height: 240))
        worktSelectView.cancelButton.addTarget(self, action: #selector(timeSelectCancelClick), for: .touchUpInside)
        worktSelectView.selectedPoints = { (value) in
            self.timeWorkAlertView?.cancleView()
            
            self.msWorkPoints = value
        self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
        }
    self.timeWorkAlertView?.initWithCustomView(worktSelectView, frame: CGRect(x: 0, y: 0, width: 280, height: 240))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeWorkAlertView!)
    }
    
    

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0{
            return 90
        }
       return 150
        
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if section ==  1 {
            return 80
        }
        return 0
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 && section == 0 && self.isHaveDetail == false {
            return 42
        }
        if self.detailModel?.ApplyState == -2 && section == 0{
            return 125
        }
        return 10
        
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        if section == 1 {
            if self.isHaveDetail == false || self.detailModel?.ApplyState == -2{
            let view = UIView()
            self.commitButton.addTarget(self, action: #selector(doCommitAction), for: .touchUpInside)
                if self.detailModel?.ApplyState == -2{
                   self.commitButton.setTitle("重新申请", for: .normal)
                }
            view.addSubview(self.commitButton)
            self.commitButton.snp.makeConstraints({ (make) in
                make.center.equalTo(view)
                make.width.equalTo(180)
                make.height.equalTo(40)
            })
            return view
         }
        }
        return nil
        
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 && self.isHaveDetail == false{
            let view = OvertimePromtView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 40))
            view.backgroundColor = UIColor.clear
            return view
        }
        if self.detailModel?.ApplyState == -2 && section == 0{
            let returnView = OvertimeReturnView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 105))
            returnView.returnReason.text = self.detailModel?.BackReason
            return returnView
        }
        let view = UIView.init()
        return view
    }
}
